import os
import json
import shutil
from typing import Dict, Any, List, Tuple
import webbrowser

class ReportGenerator:
    def __init__(self, result_json: str, output_path: str):
        self.result = self._load_json(result_json)
        self.output_path = output_path
        
    def _load_json(self, json_file: str) -> Dict:
        with open(json_file, 'r') as f:
            return json.load(f)
            
    def _format_time_ms(self, ns: int) -> float:
        return round(ns / 1000000, 2)
        
    def _generate_timeline_chart(self, data: Dict) -> str:
        # 找出主要阶段数据
        main_phases = []
        for item in data['subs']:
            if item['name'] != 'SO加载: 启动全过程中所有SO加载':
                main_phases.append(item)
        
        # 计算总启动时间
        total_time = sum(item['cost'] for item in main_phases)
        total_time_ms = self._format_time_ms(total_time)
        
        # 生成时间轴图表
        timeline_items = []
        for i, phase in enumerate(main_phases):
            phase_name = phase['name']
            duration_ms = self._format_time_ms(phase['cost'])
            percent = round((phase['cost'] / total_time) * 100, 1)
            
            # 计算颜色深浅（根据耗时百分比）
            opacity = 0.3 + (percent / 100) * 0.7
            
            # 生成子阶段HTML（如果有）
            sub_phases_html = ""
            if 'subs' in phase and phase['subs']:
                sub_items = []
                for sub in phase['subs']:
                    sub_duration_ms = self._format_time_ms(sub['cost'])
                    sub_percent = round((sub['cost'] / phase['cost']) * 100, 1)
                    sub_opacity = 0.3 + (sub_percent / 100) * 0.7
                    
                    sub_items.append(f'''
                        <div class="sub-phase" style="width: {sub_percent}%; background: rgba(65, 105, 225, {sub_opacity})">
                            <div class="phase-label">{sub['name']}</div>
                            <div class="phase-time">{sub_duration_ms}ms ({sub_percent}%)</div>
                        </div>
                    ''')
                
                sub_phases_html = f'''
                    <div class="sub-phases-container" id="sub-phases-{i}">
                        {"".join(sub_items)}
                    </div>
                '''
            
            timeline_items.append(f'''
                <div class="timeline-item">
                    <div class="phase-info">
                        <div class="phase-name" onclick="toggleSubPhases({i})">{phase_name}</div>
                        <div class="phase-metrics">{duration_ms}ms ({percent}%)</div>
                    </div>
                    <div class="phase-bar-container">
                        <div class="phase-bar" style="width: {percent}%; background: rgba(255, 140, 0, {opacity})"></div>
                    </div>
                    {sub_phases_html}
                </div>
            ''')
        
        return f'''
            <div class="timeline-container">
                <div class="timeline-header">
                    <h3>启动总耗时: {total_time_ms}ms</h3>
                </div>
                <div class="timeline-content">
                    {"".join(timeline_items)}
                </div>
            </div>
        '''
    
    def _generate_so_analysis(self, data: Dict) -> Tuple[str, str, str]:
        # 查找SO加载数据
        so_data = []
        for item in data['subs']:
            if item['name'] == 'SO加载: 启动全过程中所有SO加载':
                so_data = item['cost']
                break
        
        if not so_data:
            return "", "", ""
            
        # 按加载时间排序
        sorted_so_data = sorted(so_data, key=lambda x: x[2], reverse=True)
        
        # 分类SO
        system_so = []
        app_so = []
        for so in sorted_so_data:
            name = so[3]
            duration_ms = self._format_time_ms(so[2])
            if 'system' in name.lower():
                system_so.append((name, duration_ms))
            else:
                app_so.append((name, duration_ms))
        
        # 生成表格
        system_rows = ['<tr><th>系统SO名称</th><th>耗时(ms)</th></tr>']
        for name, duration in system_so:
            system_rows.append(f'<tr><td title="{name}">{name}</td><td>{duration}</td></tr>')
        
        app_rows = ['<tr><th>应用SO名称</th><th>耗时(ms)</th></tr>']
        for name, duration in app_so:
            app_rows.append(f'<tr><td title="{name}">{name}</td><td>{duration}</td></tr>')
        
        # 生成SO加载时间分布图表数据
        top_so = sorted_so_data[:10]  # 取耗时最长的10个SO
        chart_data = []
        for so in top_so:
            name = os.path.basename(so[3])  # 只取文件名部分
            duration_ms = self._format_time_ms(so[2])
            chart_data.append({"name": name, "value": duration_ms})
        
        chart_json = json.dumps(chart_data)
        
        # 生成饼图
        pie_chart = f'''
            <div class="chart-container">
                <canvas id="soLoadingChart" width="600" height="400"></canvas>
            </div>
            <script>
                var ctx = document.getElementById('soLoadingChart').getContext('2d');
                var chartData = {chart_json};
                
                var labels = chartData.map(function(item) {{ return item.name; }});
                var values = chartData.map(function(item) {{ return item.value; }});
                
                var backgroundColors = [
                    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
                    '#FF9F40', '#8AC249', '#EA526F', '#00A8E8', '#8675A9'
                ];
                
                new Chart(ctx, {{
                    type: 'pie',
                    data: {{
                        labels: labels,
                        datasets: [{{
                            data: values,
                            backgroundColor: backgroundColors,
                            borderWidth: 1
                        }}]
                    }},
                    options: {{
                        responsive: true,
                        title: {{
                            display: true,
                            text: 'SO加载耗时Top10分布'
                        }},
                        legend: {{
                            position: 'right',
                        }},
                        tooltips: {{
                            callbacks: {{
                                label: function(tooltipItem, data) {{
                                    var label = data.labels[tooltipItem.index];
                                    var value = data.datasets[0].data[tooltipItem.index];
                                    return label + ': ' + value + 'ms';
                                }}
                            }}
                        }}
                    }}
                }});
            </script>
        '''
        
        return '\n'.join(system_rows), '\n'.join(app_rows), pie_chart
        
    def generate(self):
        timeline_chart = self._generate_timeline_chart(self.result[0])
        system_so_table, app_so_table, so_pie_chart = self._generate_so_analysis(self.result[0])
        
        # 使用替代方法而不是format()
        html_template = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>应用启动性能分析报告</title>
            <script src="./chart.min.js"></script>
            <style>
                body {{
                    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
                    margin: 0;
                    padding: 0;
                    background-color: #f5f5f5;
                    color: #333;
                }}
                
                .container {{
                    max-width: 1200px;
                    margin: 0 auto;
                    padding: 20px;
                }}
                
                .card {{
                    background-color: white;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
                    margin-bottom: 30px;
                    padding: 20px;
                }}
                
                h1, h2, h3 {{
                    color: #333;
                    margin-top: 0;
                }}
                
                h1 {{
                    text-align: center;
                    padding: 20px 0;
                    font-size: 24px;
                    border-bottom: 1px solid #eee;
                    margin-bottom: 30px;
                }}
                
                h2 {{
                    font-size: 20px;
                    padding-bottom: 10px;
                    border-bottom: 1px solid #eee;
                    margin-bottom: 20px;
                }}
                
                /* 时间轴样式 */
                .timeline-container {{
                    margin-bottom: 30px;
                }}
                
                .timeline-header {{
                    margin-bottom: 20px;
                    text-align: center;
                }}
                
                .timeline-content {{
                    margin-bottom: 20px;
                }}
                
                .timeline-item {{
                    margin-bottom: 15px;
                }}
                
                .phase-info {{
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 5px;
                }}
                
                .phase-name {{
                    font-weight: bold;
                    cursor: pointer;
                }}
                
                .phase-name:hover {{
                    text-decoration: underline;
                }}
                
                .phase-metrics {{
                    color: #666;
                }}
                
                .phase-bar-container {{
                    width: 100%;
                    height: 25px;
                    background-color: #eee;
                    border-radius: 4px;
                    overflow: hidden;
                }}
                
                .phase-bar {{
                    height: 100%;
                    border-radius: 4px;
                }}
                
                /* 子阶段样式 */
                .sub-phases-container {{
                    display: none;
                    margin-top: 10px;
                    margin-left: 20px;
                    padding-left: 10px;
                    border-left: 2px dashed #ccc;
                    display: flex;
                }}
                
                .sub-phase {{
                    padding: 8px;
                    border-radius: 4px;
                    margin-right: 5px;
                    min-width: 80px;
                    text-align: center;
                }}
                
                .phase-label {{
                    font-size: 12px;
                    font-weight: bold;
                    margin-bottom: 5px;
                    word-break: break-word;
                }}
                
                .phase-time {{
                    font-size: 11px;
                }}
                
                /* 表格样式 */
                .tables-container {{
                    display: flex;
                    justify-content: space-between;
                    flex-wrap: wrap;
                }}
                
                .table-section {{
                    width: 48%;
                }}
                
                table {{
                    width: 100%;
                    border-collapse: collapse;
                    margin-bottom: 20px;
                }}
                
                th, td {{
                    padding: 10px;
                    text-align: left;
                    border-bottom: 1px solid #eee;
                }}
                
                th {{
                    background-color: #f9f9f9;
                    font-weight: bold;
                }}
                
                tr:hover {{
                    background-color: #f5f5f5;
                }}
                
                /* 图表容器 */
                .chart-container {{
                    margin: 20px auto;
                    max-width: 600px;
                }}
                
                /* 响应式设计 */
                @media (max-width: 768px) {{
                    .tables-container {{
                        flex-direction: column;
                    }}
                    
                    .table-section {{
                        width: 100%;
                    }}
                }}
            </style>
        </head>
        <body>
            <div class="container">
                <h1>应用启动性能分析报告</h1>
                
                <div class="card">
                    <h2>启动阶段耗时分析</h2>
                    {0}
                </div>
                
                <div class="card">
                    <h2>SO加载耗时分析</h2>
                    {3}
                    
                    <div class="tables-container">
                        <div class="table-section">
                            <h3>应用SO加载耗时</h3>
                            <table>
                                {1}
                            </table>
                        </div>
                        <div class="table-section">
                            <h3>系统SO加载耗时</h3>
                            <table>
                                {2}
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <script>
                function toggleSubPhases(index) {{
                    var subPhasesContainer = document.getElementById('sub-phases-' + index);
                    if (subPhasesContainer) {{
                        if (subPhasesContainer.style.display === 'none' || subPhasesContainer.style.display === '') {{
                            subPhasesContainer.style.display = 'flex';
                        }} else {{
                            subPhasesContainer.style.display = 'none';
                        }}
                    }}
                }}
            </script>
        </body>
        </html>
        """
        
        # 使用索引而不是命名参数
        report_content = html_template.format(
            timeline_chart,
            app_so_table,
            system_so_table,
            so_pie_chart
        )
        
        output_file = os.path.join(self.output_path, 'report.html')
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(report_content)
        # move resources to output_path/resources
        resources_path = os.path.join(os.path.dirname(__file__), 'resources')
        for file in os.listdir(resources_path):
            shutil.copy(os.path.join(resources_path, file), os.path.join(self.output_path, 'resources', file))
        # 使用浏览器打开报告
        webbrowser.open(output_file)